package com.gtmc.gclub.chat.jmessage;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gtmc.gclub.chat.bean.Result;
import com.gtmc.gclub.chat.constants.ChatConstant;
import com.gtmc.gclub.chat.constants.CommonProperties;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jmessage.api.common.model.MessageBody;
import cn.jmessage.api.common.model.MessagePayload;
import cn.jmessage.api.message.MessageClient;
import cn.jmessage.api.message.MessageType;
import cn.jmessage.api.message.SendMessageResult;

@Component(value = "messageOperator")
public class MessageOperator {

	private Logger log = LoggerFactory.getLogger(MessageOperator.class);

	@Autowired
	private CommonProperties commonProperties;

	/**
	 * 发送jmessage文本消息
	 * 
	 * @param targetUserName
	 *            接受的用户jmessage账号
	 * @param fromUserName
	 *            发送的用户jmessage账号
	 * @param content
	 *            发送的文本内容
	 * @return Result<Map> returnFlag: 1 成功 0失败 data： (失败)Map，错误内容 errorMsg;
	 *         http返回code (成功)Map, 发送的msg成功后的id
	 * 
	 */
	public Result<Map> sendSingleTextByAdmin(String targetUserName, String fromUserName, String content) {
		log.debug("Jmessage sendSingleText : " + targetUserName + " " + fromUserName + " " + content);
		MessageClient messageClient = new MessageClient(commonProperties.getAppkey(),
				commonProperties.getMasterSecret());
		Result<Map> rtn = null;

		MessageBody messageBody = MessageBody.text(content);

		MessagePayload payload = MessagePayload.newBuilder().setVersion(1).setTargetType("single")
				.setTargetId(targetUserName).setFromType("admin").setFromId(fromUserName)
				.setMessageType(MessageType.TEXT).setMessageBody(messageBody).build();

		try {
			SendMessageResult res = messageClient.sendMessage(payload);
			log.debug(res.toString());
			log.debug("Send txtMsg. Res msgId: " + res.getMsg_id());

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("msg_id", res.getMsg_id());
			rtn = new Result<Map>(1, map, null);

		} catch (APIConnectionException e) {
			log.error("Connection error. Should retry later. ", e);
			rtn = new Result<Map>(ChatConstant.RESULT_RETURN_FLAG_CONNECTION, null, null);
		} catch (APIRequestException e) {
			log.error("Error response from JPush server. Should review and fix it. ", e);
			log.info("HTTP Status: " + e.getStatus());
			log.info("Error Message: " + e.getMessage());
			JSONObject obj = new JSONObject(e.getMessage());
			JSONObject error = obj.optJSONObject("error");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", error.optInt("code"));
			map.put("message", error.optString("message"));
			rtn = new Result<Map>(0, map, String.valueOf(e.getStatus()));
			// //Gson gson = new
			// GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
			// Gson gson = new Gson();
			// TestErrorJson2 aa = gson.fromJson(e.getMessage(),
			// TestErrorJson2.class);
			// System.out.println("wuqi: " + aa);
		}
		return rtn;
	}

	public Result<Map> sendSingleTextByAdminWx(String targetUserName, String fromUserName, String content,
			String Name) {
		log.debug("Jmessage sendSingleText : " + targetUserName + " " + fromUserName + " " + content);
		MessageClient messageClient = new MessageClient(commonProperties.getAppkey(),
				commonProperties.getMasterSecret());
		Result<Map> rtn = null;

		// MessageBody messageBody = MessageBody.text();
		MessageBody messageBody = MessageBody.newBuilder().setText(content).addExtra("wxCode", fromUserName).build();

		WxMessagePayload payload = WxMessagePayload.newBuilder2().setVersion(1).setTargetType("single")
				.setTargetId(targetUserName).setFromType("admin").setFromId(fromUserName)
				.setMessageType(MessageType.TEXT).setMessageBody(messageBody).setFromName(Name).build();

		try {
			log.debug(payload.toString());
			SendMessageResult res = messageClient.sendMessage(payload);
			log.debug(res.toString());
			log.debug("Send txtMsg. Res msgId: " + res.getMsg_id());

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("msg_id", res.getMsg_id());
			rtn = new Result<Map>(1, map, null);

		} catch (APIConnectionException e) {
			log.error("Connection error. Should retry later. ", e);
			rtn = new Result<Map>(ChatConstant.RESULT_RETURN_FLAG_CONNECTION, null, null);
		} catch (APIRequestException e) {
			log.error("Error response from JPush server. Should review and fix it. ", e);
			log.info("HTTP Status: " + e.getStatus());
			log.info("Error Message: " + e.getMessage());
			JSONObject obj = new JSONObject(e.getMessage());
			JSONObject error = obj.optJSONObject("error");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", error.optInt("code"));
			map.put("message", error.optString("message"));
			rtn = new Result<Map>(0, map, String.valueOf(e.getStatus()));
			// //Gson gson = new
			// GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
			// Gson gson = new Gson();
			// TestErrorJson2 aa = gson.fromJson(e.getMessage(),
			// TestErrorJson2.class);
			// System.out.println("wuqi: " + aa);
		}
		return rtn;
	}

	/*
	 * map.put("media_id", result.getMediaId()); map.put("media_crc32",
	 * result.getMediaCrc32()); map.put("width", result.getWidth());
	 * map.put("height", result.getHeight()); map.put("format",
	 * result.getFormat()); map.put("fsize", result.getFsize());
	 */
	public Result<Map> sendImageMessage(String targetUserName, String fromUserName, Map res) {
		log.debug("Jmessage sendSingleImage : " + targetUserName + " " + fromUserName + " " + res.toString());
		Result<Map> rtn = null;
		if (res.get("media_id") == null || res.get("media_crc32") == null || res.get("width") == null
				|| res.get("height") == null || res.get("format") == null || res.get("fsize") == null

		) {

			rtn = new Result<Map>(ChatConstant.RESULT_RETURN_FLAG_DATA, null, "res is not all");
		}

		return this.sendImageMessage(targetUserName, fromUserName, (String) res.get("media_id"),
				(Long) res.get("media_crc32"), (Integer) res.get("width"), (Integer) res.get("height"),
				(String) res.get("format"), (Integer) res.get("fsize"));
	}

	public Result<Map> sendImageMessage(String targetUserName, String fromUserName, String mediaId, long mediaCrc32,
			int width, int height, String format, int fsize) {

		log.debug("Jmessage sendSingleImage : " + targetUserName + " " + fromUserName + " " + mediaId + " " + mediaCrc32
				+ " " + width + " " + height + " " + format + " " + fsize);
		MessageClient messageClient = new MessageClient(commonProperties.getAppkey(),
				commonProperties.getMasterSecret());
		Result<Map> rtn = null;

		MessageBody messageBody = new MessageBody.Builder().setMediaId(mediaId).setMediaCrc32(mediaCrc32)
				.setWidth(width).setHeight(height).setFormat(format).setFsize(fsize).build();

		MessagePayload payload = MessagePayload.newBuilder().setVersion(1).setTargetType("single")
				.setTargetId(targetUserName).setFromType("admin").setFromId(fromUserName)
				.setMessageType(MessageType.IMAGE).setMessageBody(messageBody).build();

		try {
			SendMessageResult res = messageClient.sendMessage(payload);
			// System.out.println(res.getMsg_id());
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("msg_id", res.getMsg_id());
			rtn = new Result<Map>(1, map, null);

		} catch (APIConnectionException e) {
			log.error("Connection error. Should retry later. ", e);
			rtn = new Result<Map>(ChatConstant.RESULT_RETURN_FLAG_CONNECTION, null, null);
		} catch (APIRequestException e) {
			log.error("Error response from JPush server. Should review and fix it. ", e);
			log.info("HTTP Status: " + e.getStatus());
			log.info("Error Message: " + e.getMessage());
			JSONObject obj = new JSONObject(e.getMessage());
			JSONObject error = obj.optJSONObject("error");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", error.optInt("code"));
			map.put("message", error.optString("message"));
			rtn = new Result<Map>(0, map, String.valueOf(e.getStatus()));
		}
		return rtn;
	}

	// class TestErrorJson2 {
	// /**
	// * error : {"code":899002,"message":"no such user"}
	// */
	//
	// private ErrorBean error;
	//
	// public ErrorBean getError() {
	// return error;
	// }
	//
	// public void setError(ErrorBean error) {
	// this.error = error;
	// }
	//
	// public class ErrorBean {
	// /**
	// * code : 899002
	// * message : no such user
	// */
	//
	// private int code;
	// private String message;
	//
	// public int getCode() {
	// return code;
	// }
	//
	// public void setCode(int code) {
	// this.code = code;
	// }
	//
	// public String getMessage() {
	// return message;
	// }
	//
	// public void setMessage(String message) {
	// this.message = message;
	// }
	//
	// @Override
	// public String toString() {
	// return "Result [code=" + code + ", message=" + message + "]";
	// }
	// }
	// @Override
	// public String toString() {
	// return error.toString();
	// }
	// }

}
